package org.bwgl.demo1.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class MyUp {
    @PostMapping(value = "up")
    public String up(String nickname, MultipartFile photo, HttpServletRequest request) throws IOException {
        System.out.println("nickname = " + nickname);
        System.out.println("photo = " + photo.getOriginalFilename());
        System.out.println("photo = " + photo.getContentType());
        String path = request.getServletContext().getRealPath("/up");
        saveFile(photo,path);
        return "up ok";
    }

    private void saveFile(MultipartFile photo, String path) throws IOException {
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        File file = new File(dir + "\\" + photo.getOriginalFilename());
        System.out.println("file.getAbsolutePath() = " + file.getAbsolutePath());
        photo.transferTo(file);
    }
}
